<?php

declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Users;
use \think\facade\Cache;
use ric\captcha\facade\CaptchaApi;
use tools\Email;

class User extends BaseController
{
    public function index($page = 1, $per_page = 15)
    {
        $userList = Users::withoutField('password')->paginate([
            'list_rows' => $per_page,
            'page' => $page
        ]);
        return $this->result('获取成功', $userList);
    }

    public function info()
    {
        (int)$uid = $this->request->param('uid');
        if ($this->token && $uid < 1) {
            $uid = $this->token['uid'];
        } elseif (!$this->token && $uid < 1) {
            return $this->result('用户不存在', [], 20020);
        }
        $user = Users::withoutField('password')->find($uid);
        if (!empty($user)) {
            return $this->result('获取成功', $user);
        }
        return $this->result('用户不存在', [], 20020);
    }

    public function register()
    {
        $params = $this->request->post();
        $rest = Users::register($params['username'], $params['email'], $params['password']);
        if ($rest[0]) {
            return $this->result('注册成功');
        }
        return $this->result($rest[1], [], 20000);
    }

    public function login()
    {
        $user = $this->request->post('user');
        $password = $this->request->post('password');
        $captcha_token = $this->request->post('captcha_token');
        $captcha_code = $this->request->post('captcha_code');

        $ip = $this->request->ip();

        $verifyCaptcha = Cache::get(md5($ip))['captcha'];
        if ($verifyCaptcha) {
            $captchaCheck = CaptchaApi::check($captcha_code, $captcha_token);
            if (!$captchaCheck) {
                $captcha = CaptchaApi::create();
                return $this->result(
                    '验证码错误',
                    [
                        'captcha_token' => $captcha['key'],
                        'captcha_hash' => $captcha['md5'],
                        'captcha_data' => $captcha['base64'],
                        //'captcha_code' => $captcha['code']
                    ],
                    20011
                );
            }
        }

        $res = Users::login($user, $password);
        if ($res[0]) {
            // 清除验证码
            Cache::set(md5($ip), ['captcha' => false]);
            return $this->result('登录成功', ['token' => $res[1]]);
        } else {
            $captcha = CaptchaApi::create();
            Cache::set(md5($ip), ['captcha' => true]);

            return $this->result(
                $res[1],
                [
                    'captcha_token' => $captcha['key'],
                    'captcha_hash' => $captcha['md5'],
                    'captcha_data' => $captcha['base64'],
                    //'captcha_code' => $captcha['code']
                ],
                20010
            );
        }
    }

    /**
     * 发送重置密码邮件
     */
    public function sendResetPasswordEmail()
    {
        $to = $this->request->post('email');
        $captcha_token = $this->request->post('captcha_token');
        $captcha_code = $this->request->post('captcha_code');

        $ip = $this->request->ip();

        $verifyCaptcha = Cache::get(md5($ip))['captcha'];
        if ($verifyCaptcha) {
            $captchaCheck = CaptchaApi::check($captcha_code, $captcha_token);
            if (!$captchaCheck) {
                $captcha = CaptchaApi::create();
                return $this->result(
                    '验证码错误',
                    [
                        'captcha_token' => $captcha['key'],
                        'captcha_hash' => $captcha['md5'],
                        'captcha_data' => $captcha['base64'],
                        //'captcha_code' => $captcha['code']
                    ],
                    20011
                );
            }
        }

        $user = Users::getByEmail($to);

        if (empty($user)) {
            $captcha = CaptchaApi::create();
            Cache::set(md5($ip), ['captcha' => true]);
            return $this->result('该邮箱不存在', [
                'captcha_token' => $captcha['key'],
                'captcha_hash' => $captcha['md5'],
                'captcha_data' => $captcha['base64'],
            ], 20030);
        }
        $code = Cache::get($to)['resetPwdCode'];
        if (!empty($code)) {
            $captcha = CaptchaApi::create();
            Cache::set(md5($ip), ['captcha' => true]);
            return $this->result('速度太快啦~请稍后尝试', [
                'captcha_token' => $captcha['key'],
                'captcha_hash' => $captcha['md5'],
                'captcha_data' => $captcha['base64'],
            ], 20031);
        }

        $code = random_int(100000, 999999);
        Cache::set($to, ['resetPwdCode' => $code], 60 * 5);
        $mail = new Email;
        $res = $mail->sendMail($to, '[EvoForum]重置密码', "您的验证码为：{$code},如果您未进行此操作请直接忽略！<br/><br/>验证码五分钟内有效");
        if ($res) {
            return $this->result('邮件发送成功');
        }
        return $this->result('邮件发送失败', [], 20032);
    }

    public function resetPwd()
    {
        $email = $this->request->post('email');
        $code = $this->request->post('code');
        $password = $this->request->post('password');

        $sign_code = Cache::get($email)['resetPwdCode'];
        if (empty($sign_code)) return $this->result('验证码不存在或已过期', [], 20040);
        if ((string)$sign_code !== (string)$code) return $this->result('邮箱验证码不正确', [], 20041);

        $user = Users::getByEmail($email);
        if (empty($user)) return $this->result('用户不存在', [], 20042);

        $user->password = password_hash($password, PASSWORD_DEFAULT);
        $user->save();

        Cache::delete($email);

        return $this->result('重置密码成功');
    }

    public function update()
    {
        if (!$this->token) return $this->result('尚未登录或Token错误', [], 20050);
        $uid = $this->token['uid'];
        $user = Users::find($uid);

        if (empty($user)) return $this->result('用户不存在', [], 20051);
        $params = $this->request->post();

        $user->save($params);
        return $this->result('更新成功', $user);
    }
}
